package com.example.doctorsystem.dao;

import com.example.doctorsystem.dao.PatientDao;
import com.example.doctorsystem.model.Patient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class PatientDaoImpl implements PatientDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insert(Patient patient) {
        String sql = "INSERT INTO patients(name, email, password, age, gender) VALUES (?, ?, ?, ?, ?)";
        return jdbcTemplate.update(sql, patient.getName(), patient.getEmail(), patient.getPassword(), patient.getAge(), patient.getGender());
    }

    @Override
    public Patient login(String email, String password) {
        String sql = "SELECT * FROM patients WHERE email = ? AND password = ?";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Patient.class), email, password);
    }

    @Override
    public List<Patient> findAll() {
        String sql = "SELECT * FROM patients";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Patient.class));
    }
    @Override
    public Patient getPatientById(int id) {
        String sql = "SELECT * FROM patients WHERE id = ?";
        List<Patient> list = jdbcTemplate.query(sql, (rs, rowNum) -> {
            Patient patient = new Patient();
            patient.setId(rs.getInt("id"));
            patient.setName(rs.getString("name"));
            patient.setEmail(rs.getString("email"));
            patient.setPassword(rs.getString("password"));
            return patient;
        }, id);
        return list.isEmpty() ? null : list.get(0);
    }

}

